<template>
  <s-clean-layout :title="isEdit ? '修改纪念日' : '添加纪念日'" navbar="normal">
    <view class="memorial-edit-container">
      <!-- 表单内容 -->
      <scroll-view scroll-y class="form-container">
        <!-- 联系人 -->
        <view class="form-item contact-item" @tap="selectContact">
          <template v-if="contactInfo.id">
            <view class="avatar-container">
              <image v-if="contactInfo.img" class="avatar" :src="contactInfo.img" mode="aspectFill"></image>
              <view v-else class="avatar-placeholder">
                <text>{{ getNameInitial(contactInfo.name) }}</text>
              </view>
            </view>
            <text class="contact-name">{{ contactInfo.name }}</text>
          </template>
          <template v-else>
            <text class="contact-add">点击添加成员</text>
          </template>
          <uni-icons type="right" size="16" color="#CCCCCC"></uni-icons>
        </view>

        <!-- 添加按钮 -->
        <view class="form-item add-button" @tap="addMemorialItem">
          <text class="add-text">添加</text>
        </view>

        <!-- 纪念日信息模块 -->
        <view v-for="(item, index) in memorialItems" :key="index" class="memorial-module">
          <!-- 纪念日名称 -->
          <view class="form-item">
            <input class="item-input-full" v-model="item.title" placeholder="纪念日名称" />
          </view>

          <!-- 选择日期 -->
          <view class="form-item" @tap="selectDate(index)">
            <text class="item-label">选择日期</text>
            <view class="item-value">
              <text class="date-value">{{ item.date }}</text>
              <uni-icons type="right" size="16" color="#CCCCCC"></uni-icons>
            </view>
          </view>

          <!-- 纪念日提醒 -->
          <view class="form-item" @tap="selectReminder(index)">
            <text class="item-label">纪念日提醒</text>
            <view class="item-value">
              <text class="reminder-value">{{ item.reminder }}</text>
              <uni-icons type="right" size="16" color="#CCCCCC"></uni-icons>
            </view>
          </view>

          <!-- 操作按钮区域 -->
          <view class="form-item action-buttons">
            <!-- 已有纪念日显示保存和删除按钮 -->
            <template v-if="item.id">
              <view class="action-btn save-btn" @tap="saveMemorialItem(index)">
                <text class="save-text">保存</text>
              </view>
              <view class="action-btn delete-btn" @tap="deleteMemorialItem(index)">
                <text class="delete-text">删除</text>
              </view>
            </template>
            <!-- 新增纪念日显示保存和删除按钮 -->
            <template v-else>
              <view class="action-btn save-btn" @tap="saveMemorialItem(index)">
                <text class="save-text">保存</text>
              </view>
              <view class="action-btn delete-btn" @tap="deleteMemorialItem(index)">
                <text class="delete-text">删除</text>
              </view>
            </template>
          </view>
        </view>
        
        <!-- 底部间距，确保内容不被底部保存按钮遮挡 -->
        <view style="height: 120rpx;"></view>
      </scroll-view>
      
      <!-- 底部保存按钮 -->
      <view class="bottom-save-button" @tap="saveMemorial">
        <text>保存</text>
      </view>

      <!-- 联系人选择器 -->
      <s-contact-selector
        v-model:visible="showContactSelector"
        title="选择联系人"
        :contacts="contactsList"
        :multiple="false"
        v-model="selectedContact"
        @confirm="handleContactConfirm"
      />
      
      <!-- 添加提醒选择器组件 -->
      <s-reminder-selector
        v-model:visible="showReminderSelector"
        :value="memorialItems[currentEditingIndex]?.reminder"
        @confirm="handleReminderConfirm"
      />
      
      <!-- 添加日期选择器组件 -->
      <s-datetime-picker
        v-model:visible="showDatePicker"
        :initialDate="memorialItems[currentEditingIndex]?.date || new Date()"
        mode="date"
        title="选择日期"
        @confirm="handleDateConfirm"
      />
    </view>
  </s-clean-layout>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import ContactApi from '@/sheep/api/contact/contact';
import ImportDayApi from '@/pages/contact/api/importday';

const isEdit = ref(false);
const contactInfo = ref({
  id: '',
  name: '',
  img: ''
});

// 联系人选择相关
const showContactSelector = ref(false);
const selectedContact = ref([]);
const contactsList = ref([]);

// 提醒选择器相关状态
const showReminderSelector = ref(false);
const currentEditingIndex = ref(0);

// 日期选择器相关状态
const showDatePicker = ref(false);

// 纪念日信息模块列表
const memorialItems = ref([]);

// 获取姓名首字母
const getNameInitial = (name) => {
  if (!name) return '?';
  return name.charAt(0).toUpperCase();
};

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};

// 打开联系人选择弹窗
const selectContact = () => {
  showContactSelector.value = true;
  
  // 设置当前选中的联系人
  if (contactInfo.value.id) {
    selectedContact.value = [{
      id: contactInfo.value.id,
      name: contactInfo.value.name,
      avatar: contactInfo.value.img
    }];
  } else {
    selectedContact.value = [];
  }
};

// 处理联系人选择确认
const handleContactConfirm = async (selected) => {
  if (selected.length > 0) {
    const contact = selected[0];
    contactInfo.value = {
      id: contact.id,
      name: contact.name,
      img: contact.avatar
    };
    
    // 联系人变更后，重新加载该联系人的纪念日
    if (contactInfo.value.id) {
      await loadMemorialData(contactInfo.value.id);
    }
  }
};

// 打开日期选择器
const selectDate = (index) => {
  currentEditingIndex.value = index;
  showDatePicker.value = true;
};

// 处理日期选择确认
const handleDateConfirm = (result) => {
  if (currentEditingIndex.value >= 0 && currentEditingIndex.value < memorialItems.value.length) {
    if (result && result.date) {
      memorialItems.value[currentEditingIndex.value].date = result.date;
    }
  }
};

// 打开提醒选择器
const selectReminder = (index) => {
  currentEditingIndex.value = index;
  showReminderSelector.value = true;
};

// 处理提醒选择确认
const handleReminderConfirm = (reminderValue) => {
  if (currentEditingIndex.value >= 0 && currentEditingIndex.value < memorialItems.value.length) {
    memorialItems.value[currentEditingIndex.value].reminder = reminderValue;
  }
};

// 添加纪念日项目
const addMemorialItem = () => {
  // 创建新的纪念日信息模块，不再弹出选择类型的弹窗
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const day = String(now.getDate()).padStart(2, '0');
  
  memorialItems.value.push({
    id: null,
    type: '纪念日', // 默认类型为"纪念日"
    date: `${year}-${month}-${day}`,
    reminder: '提前1天',
    title: '',
    description: '',
    repeatType: 4, // 默认设置为每年
    reminderEnabled: 1 // 默认开启提醒
  });
};

// 删除纪念日项目
const deleteMemorialItem = async (index) => {
  const item = memorialItems.value[index];
  
  // 如果是已有的纪念日（有id），则调用删除接口
  if (item.id) {
    uni.showModal({
      title: '确认删除',
      content: '确定要删除该纪念日吗？',
      success: async (res) => {
        if (res.confirm) {
          try {
            uni.showLoading({
              title: '删除中...'
            });
            
            // 获取联系人ID
            const pages = getCurrentPages();
            const currentPage = pages[pages.length - 1];
            const contactId = currentPage.options.contactId || contactInfo.value.id;
            
            if (!contactId) {
              throw new Error('联系人ID不能为空');
            }
            
            const res = await ImportDayApi.deleteImportDay({
              id: item.id,
              contactId: parseInt(contactId)
            });
            
            uni.hideLoading();
            
            if (res.code === 0) {
              memorialItems.value.splice(index, 1);
              uni.showToast({
                title: '删除成功',
                icon: 'success'
              });
              
              // 不再设置刷新标记
              // uni.setStorageSync('memorialListNeedRefresh', true);
            } else {
              throw new Error(res.msg || '删除失败');
            }
          } catch (error) {
            uni.hideLoading();
            console.error('删除纪念日失败:', error);
            uni.showToast({
              title: error.message || '删除失败',
              icon: 'none'
            });
          }
        }
      }
    });
  } else {
    // 如果是新添加的纪念日（没有id），直接从列表中删除
    memorialItems.value.splice(index, 1);
  }
};

// 保存单个纪念日项目
const saveMemorialItem = async (index) => {
  const item = memorialItems.value[index];
  
  // 验证数据
  if (!item.title) {
    uni.showToast({
      title: '请输入纪念日名称',
      icon: 'none'
    });
    return;
  }
  
  if (!item.date) {
    uni.showToast({
      title: '请选择日期',
      icon: 'none'
    });
    return;
  }
  
  // 获取联系人ID
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const contactId = currentPage.options.contactId || contactInfo.value.id;
  
  if (!contactId) {
    uni.showToast({
      title: '请选择联系人',
      icon: 'none'
    });
    return;
  }
  
  try {
    // 显示加载提示
    uni.showLoading({
      title: '保存中...'
    });
    
    // 解析提醒设置
    let reminderEnabled = 1;
    let advanceReminderDays = 1;
    let advanceReminderTime = "09:00:00";
    
    if (item.reminder.includes('不提醒')) {
      reminderEnabled = 0;
      advanceReminderDays = null;
      advanceReminderTime = null;
    } else if (item.reminder.includes('提前')) {
      reminderEnabled = 1;
      const daysMatch = item.reminder.match(/提前(\d+)天/);
      if (daysMatch) {
        advanceReminderDays = parseInt(daysMatch[1]);
      }
      
      const timeMatch = item.reminder.match(/(\d{1,2}:\d{2})/);
      if (timeMatch) {
        advanceReminderTime = timeMatch[1] + ":00";
      }
    } else if (item.reminder.includes('当天')) {
      reminderEnabled = 1;
      advanceReminderDays = 0;
      
      const timeMatch = item.reminder.match(/(\d{1,2}:\d{2})/);
      if (timeMatch) {
        advanceReminderTime = timeMatch[1] + ":00";
      }
    }
    
    // 转换日期为时间戳
    const dateTimestamp = new Date(item.date).getTime();
    
    // 构建请求参数
    const params = {
      id: item.id || null,
      contactId: parseInt(contactId),
      dayName: item.title,
      importDate: dateTimestamp,
      reminderEnabled: reminderEnabled,
      advanceReminderDays: reminderEnabled ? advanceReminderDays : null,
      advanceReminderTime: reminderEnabled ? advanceReminderTime : null,
      repeatType: 4, // 固定为每年
      remark: item.description || ""
    };
    
    // 调用添加或更新接口
    const res = await ImportDayApi.addOrUpdateImportDay(params);
    
    uni.hideLoading();
    
    if (res.code === 0) {
      // 如果是新增，更新ID
      if (!item.id && res.data) {
        memorialItems.value[index].id = res.data;
      }
      
      uni.showToast({
        title: item.id ? '更新成功' : '添加成功',
        icon: 'success'
      });
      
      // 添加：设置刷新标记，用于通知纪念日列表页面刷新
      uni.setStorageSync('memorialListNeedRefresh', true);
    } else {
      throw new Error(res.msg || '保存失败');
    }
  } catch (error) {
    uni.hideLoading();
    console.error('保存纪念日失败:', error);
    uni.showToast({
      title: error.message || '保存失败',
      icon: 'none'
    });
  }
};

// 保存所有纪念日（页面顶部的保存按钮）
const saveMemorial = async () => {
  // 验证数据
  if (memorialItems.value.length === 0) {
    uni.showToast({
      title: '请添加至少一个纪念日',
      icon: 'none'
    });
    return;
  }
  
  // 检查所有模块是否都填写了必填项
  for (let i = 0; i < memorialItems.value.length; i++) {
    const item = memorialItems.value[i];
    
    // 检查标题
    if (!item.title || item.title.trim() === '') {
      uni.showToast({
        title: `第${i+1}个纪念日名称不能为空`,
        icon: 'none'
      });
      return;
    }
    
    // 检查日期
    if (!item.date) {
      uni.showToast({
        title: `第${i+1}个纪念日日期不能为空`,
        icon: 'none'
      });
      return;
    }
  }
  
  // 检查是否有未保存的项目
  const unsavedItems = memorialItems.value.filter(item => !item.id);
  if (unsavedItems.length > 0) {
    uni.showModal({
      title: '提示',
      content: '有未保存的纪念日，是否保存？',
      success: (res) => {
        if (res.confirm) {
          // 保存所有未保存的项目
          saveAllUnsavedItems();
        } else {
          // 添加：设置刷新标记，用于通知纪念日列表页面刷新
          uni.setStorageSync('memorialListNeedRefresh', true);
          // 直接返回
          uni.navigateBack();
        }
      }
    });
  } else {
    // 添加：设置刷新标记，用于通知纪念日列表页面刷新
    uni.setStorageSync('memorialListNeedRefresh', true);
    // 没有未保存的项目，直接返回
    uni.navigateBack();
  }
};

// 保存所有未保存的项目
const saveAllUnsavedItems = async () => {
  try {
    uni.showLoading({
      title: '保存中...'
    });
    
    const unsavedItems = memorialItems.value.filter(item => !item.id);
    for (let i = 0; i < unsavedItems.length; i++) {
      const index = memorialItems.value.findIndex(item => item === unsavedItems[i]);
      if (index !== -1) {
        await saveMemorialItem(index);
      }
    }
    
    uni.hideLoading();
    
    // 设置刷新标记，用于通知纪念日列表页面刷新
    uni.setStorageSync('memorialListNeedRefresh', true);
    
    // 移除原有的事件通道通知方式
    // try {
    //   const eventChannel = uni.getOpenerEventChannel();
    //   eventChannel.emit('memorialUpdated', {});
    // } catch (e) {
    //   console.log('获取事件通道失败', e);
    // }
    
    setTimeout(() => {
      uni.navigateBack();
    }, 500);
  } catch (error) {
    uni.hideLoading();
    console.error('保存纪念日失败:', error);
    uni.showToast({
      title: error.message || '保存失败',
      icon: 'none'
    });
  }
};

// 正确放置onMounted生命周期钩子
onMounted(async () => {
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const { id, contactId, mode, contactName, contactImg } = currentPage.options;
  
  isEdit.value = mode === 'edit';
  
  // 获取联系人信息和纪念日列表
  if (contactId) {
    try {
      // 优先使用URL参数中传递的联系人信息（从联系人详情页进入的情况）
      if (contactName || contactImg) {
        console.log('从URL参数获取联系人信息');
        contactInfo.value = {
          id: contactId,
          name: decodeURIComponent(contactName || ''),
          img: decodeURIComponent(contactImg || '')
        };
      } else {
        // 如果没有URL参数，直接通过API获取联系人信息（不再依赖本地存储）
        console.log('通过API获取联系人信息');
        try {
          const res = await ContactApi.getContactDetail({
            id: contactId
          });
          
          if (res.code === 0 && res.data) {
            contactInfo.value = {
              id: res.data.id,
              name: res.data.name,
              img: res.data.img || res.data.avatar
            };
          }
        } catch (error) {
          console.error('获取联系人详情失败:', error);
        }
      }
      
      // 获取该联系人的所有纪念日
      if (contactInfo.value.id) {
        await loadMemorialData(contactInfo.value.id, id);
      }
    } catch (error) {
      console.error('获取联系人信息失败:', error);
    }
  }
  
  // 如果是从联系人详情页进入，但没有contactId参数，尝试从上一页获取
  if (!contactId && !isEdit.value && pages.length > 1) {
    const prevPage = pages[pages.length - 2];
    if (prevPage && prevPage.route.includes('contact') && prevPage.options.id) {
      try {
        // 尝试通过API获取联系人信息
        const res = await ContactApi.getContactDetail({
          id: prevPage.options.id
        });
        
        if (res.code === 0 && res.data) {
          contactInfo.value = {
            id: res.data.id,
            name: res.data.name,
            img: res.data.img || res.data.avatar
          };
          
          // 获取该联系人的所有纪念日
          await loadMemorialData(contactInfo.value.id, id);
        }
      } catch (error) {
        console.error('获取联系人详情失败:', error);
      }
    }
  }
  
  // 如果没有纪念日数据，添加一个默认的纪念日模块
  if (memorialItems.value.length === 0) {
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    
    memorialItems.value.push({
      id: null,
      type: '纪念日',
      date: `${year}-${month}-${day}`,
      reminder: '提前1天',
      title: '',
      description: '',
      repeatType: 4,
      reminderEnabled: 1
    });
  }
});

// 加载纪念日数据
const loadMemorialData = async (contactId, memorialId) => {
  if (!contactId) return;
  
  try {
    uni.showLoading({
      title: '加载中...'
    });
    
    console.log('查询纪念日列表，联系人ID:', contactId);
    const res = await ImportDayApi.queryImportDays({
      contactId: parseInt(contactId)
    });
    
    uni.hideLoading();
    
    if (res.code === 0 && res.data) {
      console.log('获取到纪念日列表:', res.data);
      
      // 如果是编辑模式且有指定ID，只显示该ID的纪念日
      if (isEdit.value && memorialId) {
        const memorial = res.data.find(item => item.id.toString() === memorialId.toString());
        
        if (memorial) {
          const reminderText = memorial.reminderEnabled ? 
            `提前${memorial.advanceReminderDays}天 ${memorial.advanceReminderTime ? memorial.advanceReminderTime.substring(0, 5) : ''}` : 
            '不提醒';
            
          memorialItems.value = [{
            id: memorial.id,
            type: '纪念日',
            date: formatDate(memorial.importDate),
            reminder: reminderText,
            title: memorial.dayName,
            description: memorial.remark || '',
            repeatType: memorial.repeatType || 4,
            reminderEnabled: memorial.reminderEnabled
          }];
        }
      } else {
        // 如果不是编辑模式或没有指定ID，显示所有纪念日
        memorialItems.value = res.data.map(memorial => {
          const reminderText = memorial.reminderEnabled ? 
            `提前${memorial.advanceReminderDays}天 ${memorial.advanceReminderTime ? memorial.advanceReminderTime.substring(0, 5) : ''}` : 
            '不提醒';
            
          return {
            id: memorial.id,
            type: '纪念日',
            date: formatDate(memorial.importDate),
            reminder: reminderText,
            title: memorial.dayName,
            description: memorial.remark || '',
            repeatType: memorial.repeatType || 4,
            reminderEnabled: memorial.reminderEnabled
          };
        });
      }
    }
  } catch (error) {
    uni.hideLoading();
    console.error('获取纪念日数据失败:', error);
    uni.showToast({
      title: '获取纪念日数据失败',
      icon: 'none'
    });
  }
};

// 格式化日期函数
const formatDate = (timestamp) => {
  if (!timestamp) return '';
  const date = new Date(timestamp);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};
</script>

<style lang="scss" scoped>
.memorial-edit-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  position: relative;
}

/* 移除原有的header样式 */
.header {
  display: none;
}

/* 修改表单容器样式 */
.form-container {
  height: calc(100vh - 44px - var(--status-bar-height));
  padding-top: 20rpx;
  box-sizing: border-box;
}

/* 底部保存按钮样式 */
.bottom-save-button {
  position: fixed;
  bottom: 20rpx;
  left: 50%;
  transform: translateX(-50%);
  width: 90%;
  height: 90rpx;
  background-color: #007AFF;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 32rpx;
  font-weight: 500;
  z-index: 100;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.2);
  border-radius: 45rpx;
  margin-bottom: env(safe-area-inset-bottom);
}

.form-item {
  display: flex;
  align-items: center;
  padding: 30rpx;
  background-color: #fff;
  margin-bottom: 2rpx;
  position: relative;
}

.contact-item {
  margin-bottom: 20rpx;
  background-color: #fff;
  border-radius: 12rpx;
  margin: 20rpx;
}

.contact-add {
  font-size: 32rpx;
  color: #333;
  flex: 1;
}

.avatar-container {
  width: 80rpx;
  height: 80rpx;
  border-radius: 40rpx;
  overflow: hidden;
  margin-right: 20rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar {
  width: 100%;
  height: 100%;
}

.avatar-placeholder {
  width: 100%;
  height: 100%;
  background-color: #B388FF;
  color: #fff;
  font-size: 32rpx;
  font-weight: bold;
  display: flex;
  align-items: center;
  justify-content: center;
}

.contact-name {
  font-size: 32rpx;
  color: #333;
  flex: 1;
}

.add-button {
  justify-content: center;
  color: #007AFF;
  margin-bottom: 20rpx;
}

.add-text {
  font-size: 32rpx;
}

.memorial-module {
  margin-bottom: 20rpx;
}

.memorial-type {
  justify-content: space-between;
  background-color: #f8f8f8;
}

.type-label {
  font-size: 36rpx;
  color: #333;
  font-weight: 500;
}

.type-actions {
  display: flex;
  gap: 20rpx;
}

.action-btn {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 操作按钮区域样式 */
.action-buttons {
  display: flex;
  justify-content: flex-end;
  padding: 20rpx 30rpx;
  background-color: #fff;
}

.action-btn {
  width: 160rpx;
  height: 60rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 6rpx;
  margin-left: 20rpx;
}

.save-btn {
  background-color: rgba(0, 122, 255, 0.1);
}

.save-text {
  color: #007AFF;
  font-size: 28rpx;
  font-weight: 500;
}

.delete-btn {
  background-color: rgba(255, 82, 82, 0.1);
}

.delete-text {
  color: #FF5252;
  font-size: 28rpx;
  font-weight: 500;
}

/* 移除冲突的样式 */
.delete-item {
  justify-content: center;
  color: #FF5252;
}

.delete-text {
  font-size: 32rpx;
}

.item-label {
  width: 200rpx;
  font-size: 32rpx;
  color: #333;
}

.item-value {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

.date-value, .reminder-value {
  font-size: 32rpx;
  color: #666;
  margin-right: 10rpx;
}

.item-input {
  flex: 1;
  height: 80rpx;
  font-size: 32rpx;
  color: #333;
  text-align: right;
}

.item-textarea {
  flex: 1;
  height: 160rpx;
  font-size: 32rpx;
  color: #333;
  text-align: right;
}

/* 联系人选择弹窗样式 */
.popup-content {
  background-color: #fff;
  border-radius: 24rpx 24rpx 0 0;
  padding-bottom: env(safe-area-inset-bottom);
}

.popup-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx;
  border-bottom: 1px solid #f0f0f0;
}

.popup-title {
  font-size: 32rpx;
  font-weight: 500;
  color: #333;
}

.popup-close {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.contact-list {
  max-height: 60vh;
  padding: 0 30rpx;
}

.contact-item {
  display: flex;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 1px solid #f0f0f0;
}

.contact-avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 40rpx;
  overflow: hidden;
  margin-right: 20rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.item-input-full {
  width: 100%;
  height: 80rpx;
  font-size: 32rpx;
  color: #333;
  padding: 0 20rpx;
}
</style>
